package persistencia;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import negocio.Area;
import negocio.Supervisor;

public class AreaDAO 
{

	private Connection c;
	private static AreaDAO instancia;
	
	private AreaDAO()
	{
		c = BDManager.getInstance().getConexion();
	}
	
	public static AreaDAO  getInstance()
	{
		if(instancia == null)
			instancia = new AreaDAO();
		return instancia;
	}
	
	public ArrayList<Area> getAll()
	{
		String query = "SELECT * FROM area";
		Statement s;
		ResultSet rs;
		ArrayList<Area> res = new ArrayList<Area>();
		try {
			s = c.createStatement();
			rs = s.executeQuery(query);
			while(rs.next())
			{
				res.add(new Area(rs.getInt(1), rs.getString(2)));
			}
			s.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return res;
	}
	
	public void guardar(Area area)
	{
		String query = "INSERT INTO area(area) VALUES ('" + area.getNombre() + "')";
		Statement s;
		try {
			s = c.createStatement();
			s.execute(query);
			s.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Area getArea(int id)
	{
		String query = "SELECT * FROM area where " + id + "=id";
		Statement s;
		ResultSet rs;
		Area res=null;
		try{
			s=c.createStatement();
			rs=s.executeQuery(query);
			rs.next();
			res=new Area(rs.getInt(1), rs.getString(2));
		}
		catch (SQLException e){
			e.printStackTrace();
		}
		
		return res;		
	}


	
	  //SE devuelve Objeto, para luego comparar si permanece null la variable o no cuando se invoca este metodo.
	  public Supervisor buscarUser(String username, String password) throws SQLException {
	    String query = String.format(
	      "select * from supervisor where nickname = '%s' and contrasenia = '%s';",
	      username, password
	    );
	    Statement s = c.createStatement();
	    ResultSet rs = s.executeQuery(query);
	    
	    Supervisor dto = null;
	
	    if (rs.next()) {
	
	      dto = new Supervisor(rs.getString("dni"), rs.getString("nombre"), rs.getString("apellido"), rs.getInt("telefono"), rs.getString("mail"),rs.getString("nickname"), rs.getString("contrasenia"));
	    }
	    s.close();
	    return dto; //si no existe devuelve null
	  }
	






}
